package com.qf.controller;

import com.qf.model.Car;
import com.qf.model.User;
import com.qf.service.CarService;
import com.qf.service.impl.CarServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/car")
public class CarController extends BaseServlet{
CarService service=new CarServiceImpl();
    public String addCar(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");
        if(user==null){
            return "REDIRECT:login.jsp";
        }
        String pid=request.getParameter("pid");
        String price=request.getParameter("price");
        Integer uid=((User)user).getId();
        Map<String,Object> map=new HashMap<>();
        map.put("pid",Integer.parseInt(pid));
        map.put("price",new BigDecimal(price));
        map.put("uid",uid);
        //insertCar
        service.addCar(map);
    //判断
        return "REDIRECT:cartSuccess.jsp";
    }




    public String getCars(HttpServletRequest request, HttpServletResponse response){
        //select * from cardetail where uid=?;
        //select * from product where pid=?
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");
        if(user==null){
            return "REDIRECT:login.jsp";
        }
        List<Car> list=null;
        list=service.getAllCar(((User)user).getId());
        request.setAttribute("list",list);
        return  "FORWARD:cart.jsp";
    }



    //修改购物车数量的
    //action=updateCar&pid="+pid+"&price="+p+"&cnum="+(nums+1),
    public String updateUpCar(HttpServletRequest request, HttpServletResponse response){
        String idstr=request.getParameter("id");
        String priceStr=request.getParameter("price");
        String cnumStr=request.getParameter("cnum");

        int a=service.changeCarNum(Integer.parseInt(idstr),new BigDecimal(priceStr),Integer.parseInt(cnumStr));

        return String.valueOf(a);
    }

    //执行购物车列表的减号功能
    public String updateDownCar(HttpServletRequest request, HttpServletResponse response){
        String idstr=request.getParameter("id");
        String priceStr=request.getParameter("price");
        String cnumStr=request.getParameter("cnum");
        String isRemove=request.getParameter("isRemove");
        int a=service.changeDownCarNum(Integer.parseInt(idstr),new BigDecimal(priceStr),Integer.parseInt(cnumStr),Boolean.parseBoolean(isRemove));
        return String.valueOf(a);
    }
}
